package com.tarry.stack;

import java.util.Objects;

/**
 * 链式栈：基于链表实现栈操作
 */
public class LinkedStack {

    // 哨兵，初始化栈顶为一个空对象
    private Node item = new Node();

    public class Node {
        public String data;
        public Node pre;
    }

    /**
     * 如栈操作
     * @param item
     * @return
     */
    public boolean push(String item){
        Node node = new Node();
        node.data = item;
        node.pre = this.item;
        this.item = node;
        return true;
    }

    /**
     * 出栈操作
     * @return
     */
    public String pop(){
        if (Objects.isNull(this.item.pre)) {
            throw new RuntimeException("the stack is empty");
        }
        String tmp = this.item.data;
        this.item = this.item.pre;
        return tmp;
    }

    public void showStack(){
        Node tmp = this.item;
        while (tmp.pre != null ){
            System.out.println(tmp.data);
            tmp = tmp.pre;
        }
    }

}
